using System.Collections.Generic;
using System.IO;
using UnityEngine;

namespace ParticleExporter
{
    [RequireComponent(typeof(Camera))]
    public class ParticleExporterCamera : MonoBehaviour
    {
        public int PngSize = 512;
        public int Fps = 30;
        public float Scale = 1;
        public string ExportPath = "ParticleSystemExport/";

        private Camera _camera = null;
        private new Camera camera => _camera ? _camera : _camera = GetComponent<Camera>();

        [MethodButton]
        public void RenderAndSave()
        {
            var es = GetExportObjects();
            foreach (var exportSettings in es)
            {
                camera.RenderParticleAndSave(exportSettings);
            }
        }
        
        private ExportSettings[] GetExportObjects()
        {
            var result = new List<ExportSettings>();
            for (var i = 0; i < transform.childCount; i++)
            {
                var child = transform.GetChild(i);
                var overwrite = child.GetComponent<ExportSettingsOverwrite>();
                var system = child.GetComponent<ParticleSystem>();
                if (!system) continue;
                
                var settings = MakeSettings(system, overwrite);
                result.Add(settings);
            }
            return result.ToArray();
        }

        private ExportSettings MakeSettings(ParticleSystem system, ExportSettingsOverwrite overwrite = null)
        {
            var settings = new ExportSettings
            {
                Fps = Fps,
                ExportPath = ExportPath,
                FilePrefix = system.name,
                PngSize = PngSize,
                rootPs = system,
                Scale = Scale,
            };
                
            if (overwrite)
            {
                if (overwrite.Size.Overwrite) settings.PngSize = overwrite.Size.Value;
                if (overwrite.Fps.Overwrite) settings.Fps = overwrite.Fps.Value;
                if (overwrite.FilePrefix.Overwrite) settings.FilePrefix = overwrite.FilePrefix.Value;
                if (overwrite.ExportPath.Overwrite) settings.ExportPath = overwrite.ExportPath.Value;
                if (overwrite.SubDir.Overwrite)
                    settings.ExportPath = Path.Join(settings.ExportPath, overwrite.SubDir.Value);
                settings.Scale = overwrite.Scale;
            }

            return settings;
        }
    }

    internal struct ExportSettings
    {
        public int PngSize;
        public int Fps;
        public string ExportPath;
        public string FilePrefix;
        public float Scale;
        public ParticleSystem rootPs;
    }
}